<template>
  <div class="role-permissions-container">
    <el-row :gutter="20">
      <!-- 角色列表 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>角色列表</span>
              <el-button
                type="primary"
                :icon="Plus"
                @click="handleAddRole"
                v-if="userStore.isAdmin"
              >
                新增角色
              </el-button>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="roles"
            border
            style="width: 100%"
            @row-click="handleRoleSelect"
            highlight-current-row
          >
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleCode" label="角色编码" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  link
                  :icon="Edit"
                  @click.stop="handleEditRole(row)"
                  v-if="userStore.isAdmin"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  :icon="Delete"
                  @click.stop="handleDeleteRole(row)"
                  v-if="userStore.isAdmin"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" :disabled="roleDialogType === 'edit'" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../api/request'
import { useUserStore } from '../store'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const roleDialogVisible = ref(false)
const roleDialogType = ref('add')
const roleFormRef = ref(null)
const roles = ref([])
const currentRole = ref(null)

const roleForm = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: ''
})

const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

const fetchRoles = async () => {
  try {
    loading.value = true
    const res = await request.get('api/roles')
    if (res.code === 200) {
      roles.value = res.data;
    } else {
      ElMessage.error(res.message || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败');
  } finally {
    loading.value = false
  }
}

const handleRoleSelect = (row) => {
  currentRole.value = row
}

const resetRoleForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  Object.assign(roleForm, {
    id: null,
    roleName: '',
    roleCode: '',
    description: ''
  })
}

const handleAddRole = () => {
  roleDialogType.value = 'add'
  resetRoleForm()
  roleDialogVisible.value = true
}

const handleEditRole = (row) => {
  roleDialogType.value = 'edit'
  Object.assign(roleForm, row)
  roleDialogVisible.value = true
}

const handleDeleteRole = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`api/roles/${row.id}`)
    ElMessage.success('删除成功')
    fetchRoles()
    if (currentRole.value?.id === row.id) {
      currentRole.value = null
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleRoleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitting.value = true
    
    if (roleDialogType.value === 'add') {
      await request.post('api/roles', roleForm)
      ElMessage.success('新增成功')
    } else {
      await request.put(`api/roles/${roleForm.id}`, roleForm)
      ElMessage.success('编辑成功')
    }
    
    roleDialogVisible.value = false
    fetchRoles()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchRoles()
})
</script>

<style scoped>
.role-permissions-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-tree) {
  margin-top: 10px;
}
</style> 